package com.olda.play.system.biz.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.olda.play.enums.ConstantEnum;
import com.olda.play.rpc.CommonResponseDto;
import com.olda.play.system.biz.SysRoleBizService;
import com.olda.play.system.biz.dao.SysRoleBizMapper;
import com.olda.play.system.dto.SysRoleDto;
import com.olda.play.system.model.dao.SysRoleMapper;
import com.olda.play.system.model.dao.SysRoleMenuMapper;
import com.olda.play.system.model.dao.SysUserRoleMapper;
import com.olda.play.system.model.po.*;
import com.olda.play.system.vo.SysDeptVo;
import com.olda.play.system.vo.SysRoleVo;
import com.olda.play.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 */
@Service
public class SysRoleBizServiceImpl implements SysRoleBizService {
    @Autowired
    private SysRoleBizMapper sysRoleBizMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 分页获取角色列表
     * @return
     */
    @Override
    public CommonResponseDto<List<SysRoleDto>> querySysRoleList(SysRoleVo param) {
        Map<String,Object> map= BeanUtil.copyProperties(param, Map.class);
        map.put("isDeleted", ConstantEnum.IS_DELETE_NO.getCode());
        int pageNum = param.getPageNum();
        int pageSize = param.getPageSize();
        PageHelper.startPage(pageNum, pageSize);
        List<SysRoleDto> list=sysRoleBizMapper.selectByCondition(map);
        PageInfo<SysRoleDto> pageInfo = new PageInfo(list);
        int count = Integer.parseInt(String.valueOf(pageInfo.getTotal()));
        if (CollectionUtils.isEmpty(list)) {
            return CommonResponseDto.success(new PageInfo<>(new ArrayList<>()));
        }
        return CommonResponseDto.success(pageInfo);
    }

    /**
     * 不分页查询角色数据
     * @param param
     * @return
     */
    @Override
    public List<SysRoleDto> querySysRoleListNoPage(SysDeptVo param) {
        Map<String,Object> map= BeanUtil.copyProperties(param, Map.class);
        map.put("isDeleted", ConstantEnum.IS_DELETE_NO.getCode());
        List<SysRoleDto> list=sysRoleBizMapper.selectByCondition(map);
        return list;
    }

    /**
     * 保存角色信息
     * @param sysRole
     */
    @Override
    public void save(SysRole sysRole) {
        sysRole.setCreateTime(new Date());
        sysRole.setCreateUser(UserUtils.getUserId().toString());
        sysRole.setCreateUserName(UserUtils.getUsername());
        sysRole.setDeleted(ConstantEnum.IS_DELETE_NO.getCode());
        sysRole.setIsDeleted(ConstantEnum.IS_DELETE_NO.getCode());
        sysRole.setPlatform(ConstantEnum.PLATEFORM_0.getCode());
        sysRoleMapper.insert(sysRole);
    }

    /**
     * 修改角色信息
     * @param sysRole
     */
    @Override
    public void updateSysRole(SysRole sysRole) {
        sysRole.setModifyTime(new Date());
        sysRole.setModifyUser(UserUtils.getUserId().toString());
        sysRole.setModifyUserName(UserUtils.getUsername());
        sysRoleMapper.updateByPrimaryKeySelective(sysRole);
    }

    /**
     * 根据角色编码获取角色信息
     * @param code
     * @return
     */
    @Override
    public SysRole getSysRoleByRoleCode(String code) {
        SysRoleExample example=new SysRoleExample();
        SysRoleExample.Criteria criteria=example.createCriteria();
        criteria.andCodeEqualTo(code);

        List<SysRole> list=sysRoleMapper.selectByExample(example);

        return list.size()>0?list.get(0):null;
    }

    /**
     * 根据角色id获取角色信息
     * @param id
     * @return
     */
    @Override
    public SysRole getSysRoleByRoleId(Long id) {
        return sysRoleMapper.selectByPrimaryKey(id);
    }

    /**
     * 给角色分配权限
     * @param id 角色id
     * @param menuIds 菜单id列表
     */
    @Override
    public void allotPerms(Long id, List<Long> menuIds) {
        //删除历史绑定关系
        deleteRoleMenuById(id,0);
        //重新绑定
        for (int i = 0; i < menuIds.size(); i++) {
            SysRoleMenu sysRoleMenu=new SysRoleMenu();
            sysRoleMenu.setRoleId(id);
            sysRoleMenu.setMenuId(menuIds.get(i));
            saveSysRoleMenu(sysRoleMenu);
        }
    }

    /**
     * 根据菜单id或者角色id删除关联关系
     * @param id
     * @param type 0、通过角色id  1、通过菜单id
     */
    @Override
    public void deleteRoleMenuById(Long id ,int type){
        SysRoleMenuExample example=new SysRoleMenuExample();
        SysRoleMenuExample.Criteria criteria=example.createCriteria();
        if(type==0){
            //先删除菜单，在删除关联关系
            sysRoleMapper.deleteByPrimaryKey(id);
            criteria.andRoleIdEqualTo(id);
        }else{
            criteria.andMenuIdEqualTo(id);
        }
        sysRoleMenuMapper.deleteByExample(example);
    }

    /**
     * 保存角色菜单关联关系
     * @param sysRoleMenu
     */
    @Override
    public void saveSysRoleMenu(SysRoleMenu sysRoleMenu) {
        sysRoleMenuMapper.insert(sysRoleMenu);
    }

    /**
     * 根据用户id获取关联的角色信息
     * @param userId
     * @return
     */
    @Override
    public List<SysRole> getSysRoleByUserId(Long userId) {
        List<SysUserRole> sysUserRoles=getSysUserRole(userId,0);
        if(sysUserRoles.size()==0){
            return new ArrayList<>();
        }
        List<Long> roleIds=sysUserRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
        SysRoleExample sysRoleExample=new SysRoleExample();
        SysRoleExample.Criteria criteria=sysRoleExample.createCriteria();
        criteria.andIdIn(roleIds);
        criteria.andIsDeletedEqualTo(0);

        List<SysRole> list=sysRoleMapper.selectByExample(sysRoleExample);
        return list;
    }

    /**
     * 根据用户id或角色id获取用户角色关联关系
     * @param id
     * @param type 0、根据用户id  1、根据角色id
     * @return
     */
    @Override
    public List<SysUserRole> getSysUserRole(Long id, Integer type) {
        SysUserRoleExample example=new SysUserRoleExample();
        SysUserRoleExample.Criteria criteria=example.createCriteria();
        if(type==0){
            criteria.andUserIdEqualTo(id);
        }else{
            criteria.andRoleIdEqualTo(id);
        }
        List<SysUserRole> list=sysUserRoleMapper.selectByExample(example);
        return list;
    }

    /**
     * 获取角色和菜单以及权限的关联关系
     * @param id
     * @param type 0、根据菜单id  1、根据角色id
     * @return
     */
    @Override
    public List<SysRoleMenu> getSysSysRoleMenu(Long id, int type) {
        SysRoleMenuExample example=new SysRoleMenuExample();
        SysRoleMenuExample.Criteria criteria=example.createCriteria();
        if(type==0){
            criteria.andMenuIdEqualTo(id);
        }else{
            criteria.andRoleIdEqualTo(id);
        }
        List<SysRoleMenu> list=sysRoleMenuMapper.selectByExample(example);
        return list;
    }
}
